import axios from 'axios'
import { Message,MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/CookiesUtil'
import router from '../../router'



let cancel ,promiseArr = {}

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 50000 // request timeout

})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    //config.headers.Authorization = `token ${store.state.user.token}`;
  }
  /*if (store.state.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = `token ${store.state.token}`;
  }*/
  console.log("request进来了")
  /*if (promiseArr[config.url]) { //发起请求时，取消掉当前正在进行的相同请求
    promiseArr[config.url]('操作取消')
    promiseArr[config.url] = cancel
  } else {
    promiseArr[config.url] = cancel
  }*/
  /*if(config.method  === 'post'){
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; //from表单数据提交
  }else {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'; //json数据
  }*/
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    console.log("response响应了")
    const res = response.data;
    // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;601未登录
    if (res.code === 50008 || res.code === 50012 || res.code === 50014|| res.code === 601) {
      MessageBox.confirm(res.message, {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.clear();// 重新登录清空所有数据
        router.replace({
          path: '/login'
        })
      })
    } else {
      return response; //如果不反悔response 就拿不到响应数据（切记）
    }
  },
  error => {
    //console.log('err' + error)// for debug
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break;
        case 401:
          error.message = '未授权，请重新登录'
          // 返回 401 清除token信息并跳转到登录页面
          store.commit(types.LOGOUT);
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
          break;
        case 403:
          error.message = '拒绝访问'
          break;
        case 404:
          error.message = '请求错误,未找到该资源'
          break;
        case 405:
          error.message = '请求方法未允许,get或者post请求不正确'
          break;
        case 408:
          error.message = '请求超时'
          break;
        case 500:
          error.message = '服务器端出错'
          break;
        case 501:
          error.message = '网络未实现'
          break;
        case 502:
          error.message = '网络错误'
          break;
        case 503:
          error.message = '服务不可用'
          break;
        case 504:
          error.message = '网络超时'
          break;
        case 505:
          error.message = 'http版本不支持该请求'
          break;
        default:
          error.message = `连接错误${err.response.status}`
      }
    } else {
      error.message = "连接到服务器失败"
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 10000
    })
    return Promise.reject(error)
  })

export default service
